#json !/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import datetime
reload(sys) 
sys.setdefaultencoding('utf8')
import time
import MySQLdb
sys.path.insert(0,'/home/liuyue/svn/wan/')
sys.path.insert(0,'/opt/web/')
sys.path.insert(0,'/opt/wanalytics/')
from Tools import connectMySQL
from datetime import date
from datetime import timedelta
import calendar

def Total():
    
    
    
    
    _yesday = datetime.datetime.today() + datetime.timedelta(-1)
    _datetime = _yesday.strftime('%Y%m%d')
    #_datetime = "20120920"
    
    yy = _datetime[0:4]
    mm = _datetime[4:6]
    dd = _datetime[6:]
    
    sdd,e_day = calendar.monthrange(int(yy),int(mm))
        
    start_day = "%s%s%s" % (yy,mm,'01')
    end_day = "%s%s%s" % (yy,mm,e_day)
    _date = "%s%s" % (yy,mm)
    
    #_datesql = " "
    #数据库连接
    try:
        db = connectMySQL.connMySQL("stat")
    except MySQLdb.Error, e:
        resultStr = '{"status": "failed", "code": "4001", "str": "connect database failed"}'
        return resultStr
    db.autocommit(True)
    c = db.cursor()
    
    sql = " SELECT sum(total_download_add),sum(total_download_num),app_id FROM `stat_oper_board` where date >= %s and date <= %s  group by app_id " % (start_day,end_day)
    #print sql
    c.execute(sql)  
    result = c.fetchall()
                
    for x in result:
        sql = " insert into `stat_oper_board_month` (`date`,`app_id`,`total_download_add`,`total_download_num`,`start_date`,`end_date`) values ('%s','%s','%s','%s','%s','%s') " % (_date,int(x[2]),int(x[0]),int(x[1]),start_day,end_day)
        try:
            c.execute(sql)
        except Exception,e:
            c.execute("update stat_oper_board_month set total_download_add = %s,total_download_num = %s where date = %s and app_id = %s and start_date = %s and end_date = %s  " % (int(x[0]),int(x[1]),_date,int(x[2]),start_day,end_day))
    c.close()
    db.close()
    
    
    





if __name__ == '__main__':
    cmd = ''
    if len(sys.argv) == 2:
        cmd = sys.argv[1]

    Total()
    print "Done !"
